import { useIntl } from '@umijs/max';
import { Flex, Space, Spin } from 'antd';
import type { DescriptionsItemType } from 'antd/es/descriptions';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useDeviceInfo, useIsFresh, useSelectedDeviceNode } from '../SelectedDeviceNodeContext';

import Description from '@/components/Description';
import { realTimeMonitoringControllerPcsRealtimeData } from '@/services/ess/realTimeMonitoring';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';

export const Info: React.FC = () => {
  const { isRefesh, setIsRefesh } = useIsFresh();
  const deviceNode = useSelectedDeviceNode();
  const { setDeviceInfo } = useDeviceInfo();
  const intl = useIntl();

  const OnlineOptions = useRef<any>(null);
  const WorkOptions = useRef<any>(null);
  const BreakStatusOptions = useRef<any>(null);
  const BreakBreakdownOptions = useRef<any>(null);
  const [loading, setLoading] = useState<boolean>(true);

  const columnsCopy = [
    // 1
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.onlineStatus',
      }),
      key: 'onlineState',
      children: '',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.workingStatus',
      }),
      children: '',
      key: 'workState',
    },
    {
      label: '',
      children: '',
      key: 'disabled',
      hidden: true,
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.igbtTempA',
      }),
      children: '',
      key: 'igbta',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.igbtTempB',
      }),
      children: '',
      key: 'igbtb',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.igbtTempC',
      }),
      children: '',
      key: 'igbtc',
    },
    // 2
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.voltageA',
      }),
      children: '',
      key: 'ua',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.voltageB',
      }),
      children: '',
      key: 'ub',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.voltageC',
      }),
      children: '',
      key: 'uc',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.currentA',
      }),
      children: '',
      key: 'ia',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.currentB',
      }),
      children: '',
      key: 'ib',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.currentC',
      }),
      children: '',
      key: 'ic',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.activePower',
      }),
      children: '',
      key: 'activePower',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.reactivePower',
      }),
      children: '',
      key: 'reactivePower',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.apparentPower',
      }),
      children: '',
      key: 'apparentPower',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.powerFactor',
      }),
      children: '',
      key: 'powerFactor',
    },
    {
      label: intl.formatMessage({
        id: 'pcsMonitoring.gridFrequency',
      }),
      children: '',
      key: 'gridFreq',
    },
    {
      label: '',
      children: '',
      key: 'disabled',
      hidden: true,
    },
    {
      label: intl.formatMessage({
        id: 'data.vdc',
      }),
      children: '',
      key: 'udc',
    },
    {
      label: intl.formatMessage({
        id: 'data.idc',
      }),
      children: '',
      key: 'idc',
    },
    {
      label: intl.formatMessage({
        id: 'data.pdc',
      }),
      children: '',
      key: 'pdc',
    },
  ];
  const [columns, setColumns] = useState<DescriptionsItemType[]>(columnsCopy);
  /**
   * 改变pcs名称
   * @param value
   */
  const changePCS = (data) => {
    const newArrayData: any[] = [];
    let FormatterData = data || {};
    // 映射在线状态
    const onlineState =
      FormatterData?.onlineState || FormatterData?.onlineState === 0
        ? (OnlineOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.onlineState);
          })?.label
        : '--';
    console.log('xsdfjsdklfjsd ');
    FormatterData.onlineState = onlineState || '';
    // 映射工作状态
    const workState = FormatterData.workState
      ? (WorkOptions?.current || []).find((item) => {
          return Number(item.value) === Number(FormatterData.workState);
        })
      : '--';
    FormatterData.workState = workState?.label || '';
    // 映射断路器状态
    const stateInfo = FormatterData.stateInfo
      ? (BreakStatusOptions?.current || []).find((item) => {
          return Number(item.value) === Number(FormatterData.stateInfo);
        })
      : '--';
    FormatterData.stateInfo = stateInfo?.label || '';
    // 映射断路器故障
    const faultInfo = FormatterData.faultInfo
      ? (BreakBreakdownOptions?.current || []).find((item) => {
          return Number(item.value) === Number(FormatterData.faultInfo);
        })
      : '--';
    FormatterData.faultInfo = faultInfo?.label || '';
    columnsCopy.forEach((item) => {
      newArrayData.push({
        ...item,
        children:
          FormatterData[item.key] || FormatterData[item.key] === 0 ? FormatterData[item.key] : null,
      });
    });
    setColumns(newArrayData.filter((res) => res.children));
  };

  const getDictOptions = () => {
    setLoading(true);
    Promise.all([
      fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.WORK_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.BREAKER_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.BREAKER_BREAKDOWN),
    ]).then((res) => {
      OnlineOptions.current = res[0];
      WorkOptions.current = res[1];
      BreakStatusOptions.current = res[2];
      BreakBreakdownOptions.current = res[3];

      realTimeMonitoringControllerPcsRealtimeData({
        areaId: deviceNode?.areaId?.toString() ?? undefined,
        deviceCode: deviceNode?.deviceCode ?? undefined,
        deviceName: deviceNode?.deviceName ?? undefined,
        deviceType: deviceNode?.deviceType ?? undefined,
      }).then((res) => {
        setLoading(false);
        setDeviceInfo({
          ts: res?.data?.ts ?? undefined,
          onLine:
            res?.data?.onlineState || String(res?.data?.onlineState) === '0'
              ? String(res?.data?.onlineState)
              : undefined,
        });
        changePCS(res?.data);
      });
      console.log('我看下转换的东西', res);
    });
  };
  useEffect(() => {
    getDictOptions();
  }, [deviceNode]);

  useEffect(() => {
    if (isRefesh) {
      console.log('Refreshing change pile data...');
      getDictOptions();
      setIsRefesh(false);
    }
  }, [isRefesh]);

  const groupColumns = useMemo(() => {
    return [columns.slice(0, 9), columns.slice(9, 15), columns.slice(15)];
  }, [columns]);

  return (
    <Spin spinning={loading}>
      <Flex vertical={true} justify={'center'} style={{ marginTop: 20, padding: '0 20px' }}>
        <Space direction="vertical" size={50} style={{ margin: '48px 0' }}>
          {groupColumns.map((item, index) => {
            return (
              <Description
                column={{ xxl: 3, xl: 3, md: 2, sm: 1 }}
                key={index}
                items={item}
              ></Description>
            );
          })}
        </Space>
      </Flex>
    </Spin>
  );
};
